﻿using BySoft.Server.Business;
using BySoft.Server.Business.UserCode;
using BySoft.Server.Common;
using BySoft.Server.Common.Entity;
using BySoft.Server.Common.Enum;
using BySoft.Server.Consts;
using BySoft.Web.Utility;
using OneSoft.EntityCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BySoft.Web.Site.Plan
{
    public partial class MatRequirementAdd : AuthBasePage
    {
        public string sequenceName { get { return "BS_MaterialRequirement" + DateTime.Now.ToString("yyyy-MM-dd"); } }
        public DataTable MaterialRequirementDetailDT
        {
            set { Session["MaterialRequirementDetailDT"] = value; }
            get
            {
                if (Session["MaterialRequirementDetailDT"] == null)
                {
                    return CreateDT();
                }
                else
                {
                    return (DataTable)Session["MaterialRequirementDetailDT"];
                }
            }
        }
        public DataTable CreateDT()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("MaterialRequirementDetailID");
            dt.Columns.Add("PlanDetailID");
            dt.Columns.Add("IsDirect");
            dt.Columns.Add("MaterialID");
            dt.Columns.Add("MaterialName");
            dt.Columns.Add("Specifications");
            dt.Columns.Add("Unit");
            dt.Columns.Add("MMNumber");//单件毫米数
            dt.Columns.Add("MeterWeight");//每米重量
            dt.Columns.Add("TotalNum");//总需求量
            dt.Columns.Add("StockNum");//库存数量
            dt.Columns.Add("OnWayNum");//在途数量
            dt.Columns.Add("MinOrderWeight");//最小送货量
            dt.Columns.Add("AdviseNum");//建议请购数量（毫米数）
            dt.Columns.Add("PieceNum");//件数
            dt.Columns.Add("Weight");//重量
            dt.Columns.Add("IsNew");
            dt.Columns.Add("IsDel");
            return dt;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                MaterialRequirementDetailDT = null;
                this.lblMaterialRequirementID.Text = ClsComm.GetMaxSequenceID(sequenceName, "PD" + DateTime.Now.ToString("yyMMdd"), 3);
               
            }
            txtPlanID.Attributes.Add("readonly", "true");
            cpBillDate.Value = DateTime.Now.ToString("yyyy-MM-dd");
            Master.ValidationGroup = "gSubmit";
        }

        private void BindGridView()
        {
            DataView dv = new DataView(MaterialRequirementDetailDT);
            dv.RowFilter = " IsDel <> '1'";
            //dv.Sort = "BOMDetailID ";
            DataTable dt = dv.ToTable();
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (CommonMethod.GetString(dr["IsDirect"]) == "1")
                    {
                        decimal MMNumber = CommonMethod.ConvertToDecimal(dr["MMNumber"]);
                        decimal MeterWeight = CommonMethod.ConvertToDecimal(dr["MeterWeight"]);
                        decimal AdviseNum = CommonMethod.ConvertToDecimal(dr["AdviseNum"]);
                        if (MMNumber != 0)
                        {
                            dr["PieceNum"] = Math.Round(AdviseNum / MMNumber, 2);
                        }
                        if (MeterWeight != 0)
                        {
                            dr["Weight"] = Math.Round(AdviseNum / 1000 / MeterWeight, 2);
                        }
                    }
                }
                grdResult.DataSource = dt;
                grdResult.DataBind();
            }
            else
            {
                UIHelper.BindEmptyGridView(grdResult, dt);
            }
            UIHelper.RunScript(this.UpdatePanel4, "iframeAutoFit();");
        }


        private void AddPro()
        {
            MaterialRequirementDetailDT = GetAddPro(MaterialRequirementDetailDT).Copy();
        }

        private DataTable GetAddPro(DataTable dt)
        {
            DataTable dtTemp = dt.Copy();
            foreach (GridViewRow gvr in grdResult.Rows)
            {
                if (gvr.RowType == DataControlRowType.DataRow)
                {
                    Label lblMaterialRequirementDetailID = gvr.FindControl("lblMaterialRequirementDetailID") as Label;
                    Label lblPlanDetailID = gvr.FindControl("lblPlanDetailID") as Label;
                    Label lblIsDirect = gvr.FindControl("lblIsDirect") as Label;
                    Label lblMaterialID = gvr.FindControl("lblMaterialID") as Label;
                    Label lblMaterialName = gvr.FindControl("lblMaterialName") as Label;
                    Label lblSpecifications = gvr.FindControl("lblSpecifications") as Label;
                    Label lblUnit = gvr.FindControl("lblUnit") as Label;
                    Label lblMMNumber = gvr.FindControl("lblMMNumber") as Label;
                    Label lblMeterWeight = gvr.FindControl("lblMeterWeight") as Label;
                    Label lblTotalNum = gvr.FindControl("lblTotalNum") as Label;
                    Label lblStockNum = gvr.FindControl("lblStockNum") as Label;
                    Label lblOnWayNum = gvr.FindControl("lblOnWayNum") as Label;
                    Label lblMinOrderWeight = gvr.FindControl("lblMinOrderWeight") as Label;
                    TextBox txtAdviseNum = gvr.FindControl("txtAdviseNum") as TextBox;
                    TextBox txtPieceNum = gvr.FindControl("txtPieceNum") as TextBox;
                    TextBox txtWeight = gvr.FindControl("txtWeight") as TextBox;
                    DataRow[] drs = dtTemp.Select("MaterialID='" + lblMaterialID.Text.Trim() + "'");
                    if (drs.Length > 0)
                    {
                        drs[0]["MaterialRequirementDetailID"] = GetGridViewString(lblMaterialRequirementDetailID);
                        drs[0]["PlanDetailID"] = GetGridViewString(lblPlanDetailID);
                        drs[0]["IsDirect"] = GetGridViewString(lblIsDirect);
                        drs[0]["MaterialID"] = GetGridViewString(lblMaterialID);
                        drs[0]["MaterialName"] = GetGridViewString(lblMaterialName);
                        drs[0]["Specifications"] = GetGridViewString(lblSpecifications);
                        drs[0]["Unit"] = GetGridViewString(lblUnit);
                        drs[0]["MMNumber"] = lblMMNumber.Text.Trim();
                        drs[0]["MeterWeight"] = lblMeterWeight.Text.Trim();
                        drs[0]["TotalNum"] = GetGridViewString(lblTotalNum);
                        drs[0]["StockNum"] = GetGridViewString(lblStockNum);
                        drs[0]["OnWayNum"] = GetGridViewString(lblOnWayNum);
                        drs[0]["MinOrderWeight"] = GetGridViewString(lblMinOrderWeight);
                        drs[0]["AdviseNum"] = GetGridViewString(txtAdviseNum);
                        drs[0]["PieceNum"] = GetGridViewString(txtPieceNum);
                        drs[0]["Weight"] = GetGridViewString(txtWeight);
                    }
                }
            }
            return dtTemp;
        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete + "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
            }
        }

        protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strCode = e.CommandArgument.ToString();
            string[] strs = strCode.Split(',');
            switch (e.CommandName)
            {
                case "del":
                    AddPro();
                    DataTable dt = MaterialRequirementDetailDT;
                    DataRow[] dr = dt.Select("PlanDetailID='" + strCode + "'");
                    if (dr != null && dr.Length > 0)
                    {
                        dr[0]["IsDel"] = "1";
                    }
                    MaterialRequirementDetailDT = dt.Copy();
                    BindGridView();
                    UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
                    break;
                default:
                    break;
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(CurrentUser.UserID))
                {
                    UIHelper.AlertMessage(this.Page, "等待时间太久，请重新填写！");
                    return;
                }
                if (!string.IsNullOrEmpty(this.lblMaterialRequirementID.Text.Trim()) && !BsMaterialRequirementBusiness.IsExistsMaterialRequirementID(lblMaterialRequirementID.Text.Trim()))
                {
                    BsMaterialrequirementEntity entity = new BsMaterialrequirementEntity();
                    entity.MaterialRequirementID = GetString(lblMaterialRequirementID);
                    entity.PlanID = GetString(txtPlanID);
                    entity.BillDate = GetDateTime(cpBillDate);
                    entity.WorkOrderNo = GetString(hdWorkOrderNo);
                    entity.Remark = GetString(txtRemark);
                    entity.Status = "1";
                    entity.CreateDate = DateTime.Now;
                    entity.CreateUserID = CurrentUser.UserID;
                    entity.CreateUserName = CurrentUser.UserName;
                    entity.ModifyDate = DateTime.Now;
                    entity.ModifyUserID = CurrentUser.UserID;
                    entity.ModifyUserName = CurrentUser.UserName;

                    AddPro();

                    if (BsMaterialRequirementBusiness.SaveOrUpdate(entity, MaterialRequirementDetailDT, "Save"))
                    {
                        ClsComm.SetMaxSequenceID(sequenceName);
                        base.LogAction(BaseEnum.ActionType.Add, entity.PlanID, true, null, new EntityBase[] { entity });
                        UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../Plan/MatRequirementList.aspx");
                    }
                    else
                    {
                        UIHelper.AlertMessage(this.Page, Message.SaveFail);
                    }
                }
                else
                {
                    UIHelper.AlertMessage(this.Page, "原料需求计划单编号已存在！");
                    ClsComm.SetMaxSequenceID(sequenceName);
                    return;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnHidden_Click(object sender, EventArgs e)
        {
            AddPro();
            BindGridView();
        }
    }
}